package com.hiof.servercommunication.auth;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import com.hiof.Configuration;
import com.hiof.activities.ANTPlusDemo;
import com.hiof.activities.LoginActivity;
import com.hiof.activities.RaceListActivity;
import com.hiof.servercommunication.RestFulServiceManager;
import com.hiof.servercommunication.exception.NetworkException;
import com.hiof.servercommunication.exception.ServerException;
import com.hiof.servercommunication.push.beans.LoginPacket;
import com.hiof.servercommunication.status.LoginStatus;
import com.hiof.utility.Utility;

/**
 * Created by IntelliJ IDEA.
 * User: manish
 * Date: 3/23/12
 * Time: 10:41 AM
 * To change this template use File | Settings | File Templates.
 */
public class LoginTask extends AsyncTask <LoginPacket, Integer, Integer>{
    @Override
    protected Integer doInBackground(LoginPacket... packet) {
        int returnVal = 0;
        String userName="";
        String password="";

        for(LoginPacket pkt:packet){
            userName = pkt.getUserName();
            password = pkt.getPassword();
        }
        if(Utility.hasNetwork() && !userName.trim().equals("") && !password.trim().equals("")){
            try {
                LoginStatus status = RestFulServiceManager.getInstance().logIn(userName, password);
                if(status==LoginStatus.OK){
                    returnVal = 1;
                } else if(status == LoginStatus.UsernamePasswordNotMatch){
                    returnVal = 2;
                } else if(status == LoginStatus.UserNotExist){
                    returnVal = 3;
                }
            } catch (NetworkException e) {
                Utility.error(this.getClass().toString(), e.getMessage());
            } catch (ServerException e) {
                Utility.error(this.getClass().toString(), e.getMessage());
            }
        }
        return returnVal;
    }

    @Override
    protected void onPostExecute(Integer status) {
        super.onPostExecute(status);
        Context ctx = Configuration.getInstance().getCurrentContext();
        Intent intent = new Intent();
        if(status==1){
            Utility.debug(this.getClass().getName(), "Successfully Logged in. Going to RaceListActivity");
//            intent.setClass(ctx, ANTPlusDemo.class);
            intent.setClass(ctx, RaceListActivity.class);

        } else{
            intent.setClass(ctx, LoginActivity.class);
            Utility.debug(this.getClass().getName(), "Invalid login. Going to LoginActivity");
        }
        ctx.startActivity(intent);
       ((Activity)ctx).finish();

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }
}
